/**
 * Created by inhere on 2016/5/6.
 */

var docView = {
  data : {
    rawSuffix: '.md',
    outSuffix: '.html'
  },
  catalogBox: function() {
    // catalog box height
    var dCatalog = $("#doc-catalog");
    var cssTop = dCatalog.css('top');
    var height = $(window).height() - 10 - cssTop.substr(0, cssTop.length - 2) * 1;
    dCatalog.css('max-height', height);
    $(window).resize(function(){
      var wHeight = $(window).height();
      var height = wHeight - 10 - cssTop.substr(0, cssTop.length - 2) * 1;
      dCatalog.css('max-height', height);
    });
    dCatalog.affix({
        offset: {
          top: 150,
          bottom: $('footer').outerHeight(true)
      }
    });

    return this;
  },
  catalogNav: function() {
    var baseUrl = GVar.pageData.baseUrl,
        self = this;

    $("#doc-catalog").find('a').each(function(index, ele){
      var old = $(ele).attr('href');

      // empty or equal to 'javascript:' or first char is '#'
      if ( !old || old.substr(0,11) == 'javascript:' || old[0] == '#') {
        return;
      }

      var now = baseUrl ? baseUrl + old : old,
          path = GVar.pageData.pagePath,
          suffix = self.data.rawSuffix;

      if (GVar.clearSuffix(path, suffix) == GVar.clearSuffix(now, suffix)) {
        $(ele).parent().addClass('active');
      }

      // 替换 后缀
      if ( now.indexOf('.') < 0) {
        now = now + self.data.outSuffix;
      } else if ( now.substr(-3) == self.data.rawSuffix ) {
        now = now.substr(0,now.length - 3) + self.data.outSuffix;
      }

      $(ele).attr('href', now);
    });

    return self;
  }
};

$(function(){
  var content = $('.article-content'),
    links  = content.find('a'),
    table = content.find('table');

  GVar.pageControl();
  GVar.makeTOC(content).contentTitleHandle(content);

  $('.enlarge-font').on('click', function () {
    GVar.controlFontSize(content, true);
  });
  $('.decrease-font').on('click', function () {
    GVar.controlFontSize(content, false);
  });

  // table add class table table-bordered
  if (table[0]) {
    table.addClass('table table-bordered');
  }

  // handle a link href
  links.each(function(index, ele){
    console.log(index, ele);
    // var old = $(ele).attr('href'),
    //     length = old.length;
    if ( $(ele).attr('href') && $(ele).attr('href').indexOf('http') === 0) {
      $(ele).attr('target', '_blank');
    }
  });

  docView.catalogBox().catalogNav();

});

